import { Component, OnInit, ViewChild } from '@angular/core';
import { Params, ActivatedRoute, Router } from '@angular/router';
import { ControlApiService } from '@core/controlApi.service';
import { DatePipe } from '@angular/common';
import { LocalStorage } from '@core/local.storage';
import { FarmReactComponent } from '../../../layout/components/farmreact.component';
import { _HttpClient } from '@delon/theme';
import { environment } from '../../../../environments/environment';
declare const echarts: any;

@Component({
    selector: 'app-detectalarm',
    templateUrl: './detectalarm.component.html',
    styleUrls: ['./detectalarm.component.less']
})

export class DetectalarmComponent implements OnInit {
    @ViewChild('farmReact', { static: false }) farmReact: FarmReactComponent;
    page = 1;
    limit = 10;
    alarmTotal = 0;
    alarmList: any = [];
    sblxIf = true;
    // sblxValue: any;
    bjlxValue: any;
    bjlxList: any = [];
    bjjbValue: any;
    bjjbList: any = [];
    // bjsbValue: any;
    shijianStartValue: any;
    shijianEndValue: any;
    listload = false;
    farmreact = false;
    selectClass = 'defaultSelect';
    showHeader = true;
    themeClass: any = {
        'control': true,
        'detectalarm': false,
        'whitetheme': true
    };
    contentClass = {
        contwrap: true,
        contwrap2: false,
        bjlb: true,
    };
    showTable = true;
    chartClass: any = {};
    tableHeight = false;
    tableContainnerHeight = false;

    shijianStartValue2: any;
    shijianEndValue2: any;
    echartsTypeValue = 'line';
    groupTypeValue = 'workshop';
    echarsWrap = { 'width': '100%', 'height': '800px', 'margin': '10px 0 0 0' };

    constructor(
        private controlApiService: ControlApiService,
        private datePipe: DatePipe,
        private activatedRoute: ActivatedRoute,
        private http: _HttpClient,
        public ls: LocalStorage,
        private router: Router
    ) { }

    ngOnInit() {
        this.activatedRoute.params.subscribe((params: Params) => {
            if (params.showHeader === 'false') {
                this.showHeader = false;
                this.themeClass = {
                    'control': false,
                    'detectalarm': true,
                    'whitetheme': true
                };
            }
            if (params.showTable === 'false') {
                this.showTable = false;
                this.contentClass = {
                    contwrap: false,
                    contwrap2: true,
                    bjlb: true,
                };
            } else if (params.showTable === 'true') {
                this.showTable = true;
                this.limit = 50;
                this.tableHeight = true;
                this.tableContainnerHeight = true;
                this.contentClass = {
                    contwrap: false,
                    contwrap2: true,
                    bjlb: true
                };
            }
            if (params.showChart === 'false') {
                this.chartClass = {
                    contwrap2: true
                };
            } else if (params.showChart === 'true') {
                this.chartClass = {
                    contwrap2: true
                };
            } else {
                this.chartClass = {
                    contwrap: true
                };
            }
        });
        this.farmreact = true;
        this.shijianStartValue = this.datePipe.transform(new Date().getTime() - 604800000, 'yyyy-MM-dd');
        this.shijianEndValue = this.datePipe.transform(new Date().getTime(), 'yyyy-MM-dd');
        this.shijianStartValue2 = this.datePipe.transform(new Date().getTime() - 604800000, 'yyyy-MM-dd');
        this.shijianEndValue2 = this.datePipe.transform(new Date().getTime(), 'yyyy-MM-dd');

        // 报警级别
        this.bjjbList = [
            { 'id': '0', 'text': '--请选择--' },
            { 'id': '1', 'text': 'I级报警' },
            { 'id': '2', 'text': 'II级报警' },
            { 'id': '3', 'text': 'III级报警' },
            { 'id': '4', 'text': '预警' }
        ];
        this.bjjbValue = this.bjjbList[0].id;
        this.bjlxList = [
            { 'id': '0', 'text': '--请选择--' },
            { 'id': 'expertsystem$alarm', 'text': '智能报警' },
            { 'id': 'alarmtable', 'text': '监测报警' },
            { 'id': 'expertsystem$prealarm', 'text': '智能预警' }
        ];
        this.bjlxValue = this.bjlxList[0].id;
        setTimeout(() => {
            this.searchType();
            this.searchStat();
        }, 500);
    }

    themeChenge(e) {
        this.farmreact = false;
        this.themeClass = 'control ' + e;
        switch (e) {
            case 'blacktheme':
                this.selectClass = 'controlSelect';
                break;
            case 'whitetheme':
                this.selectClass = 'defaultSelect';
                break;
        }
        setTimeout(() => {
            this.farmreact = true;
        }, 500);
    }

    searchType() {
        let data = '';
        const loginInfo = JSON.parse(this.ls.get('loginInfo'));
        data += '&beginTime=' + new Date(this.datePipe.transform(this.shijianStartValue, 'yyyy-MM-dd') + ' 00:00:00').getTime() / 1000;
        data += '&endTime=' + new Date(this.datePipe.transform(this.shijianEndValue, 'yyyy-MM-dd') + ' 23:59:59').getTime() / 1000;

        this.listload = true;
        this.farmReact.childOuter((res) => {
            if (res.chejianValue !== '0') {
                data += '&workshop=' + (res.chejianValue || '');
            }
            if (res.gongquValue !== '0') {
                data += '&workarea=' + (res.gongquValue || '');
            }
            if (res.chezhanValue !== '0') {
                data += '&stationid=' + (res.chezhanValue || '');
            }
        });
        if (this.bjlxValue && this.bjlxValue !== '0') {
            data += '&alarmfromtable=' + this.bjlxValue;
        }
        if (this.bjjbValue && this.bjjbValue !== '0') {
            data += '&alarmlevel=' + this.bjjbValue;
        }
        if (loginInfo.N_LEVEL === 10 || loginInfo.N_LEVEL === 30) {
            data += '&userlevel=' + loginInfo.N_LEVEL;
        }
        data += '&org=' + loginInfo.VC_ORG$ID;

        this.alarmList = [];
        this.alarmTotal = 0;

        this.alarmTabQuery(data, this.page, this.limit).subscribe((res: any) => {
            if (res.msg === 'Ok') {
                this.alarmTotal = res.count;
                if (res.data.length) {
                    for (let i = 0; i < res.data.length; i++) {
                        this.alarmList.push(res.data[i]);
                        if (res.data[i].uTime) {
                            this.alarmList[i].nTime = this.datePipe.transform(res.data[i].uTime * 1000, 'yyyy-MM-dd HH:mm:ss');
                        }
                        if (res.data[i].eTime) {
                            this.alarmList[i]._eTime = this.datePipe.transform(res.data[i].eTime * 1000, 'yyyy-MM-dd HH:mm:ss');
                        }
                        this.alarmList[i].num = (this.page - 1) * this.limit + i + 1;
                    }
                }
                setTimeout(() => {
                    this.listload = false;
                }, 500);
            }
        });
    }

    // 报警信息列表
    alarmTabQuery(data, page, limit) {
        let url = environment.project + '/alarmTab2/query?page=' + page + '&limit=' + limit;
        if (data) {
            url += data;
        }
        return this.http.get(url);
    }
    searchStat() {
        const beginTime = new Date(this.datePipe.transform(this.shijianStartValue2, 'yyyy-MM-dd') + ' 00:00:00').getTime() / 1000;
        const endTime = new Date(this.datePipe.transform(this.shijianEndValue2, 'yyyy-MM-dd') + ' 23:59:59').getTime() / 1000;
        this.alarmTabcharts(this.echartsTypeValue, this.groupTypeValue, beginTime, endTime).subscribe((res: any) => {
            res.series[0].barWidth = 30;
            res.grid = { 'left': 80, 'right': 0, 'top': 30, 'bottom': 20 };
            echarts.init(document.getElementById('echarsAlarm')).setOption(res);
            this.listload = false;
        });
    }
    // 报警统计图形
    alarmTabcharts(type, groupby, begintime, endtime) {
        const url = environment.project + '/alarmTab2/charts';
        const params = JSON.stringify({ 'type': type, 'groupby': groupby, 'begintime': begintime, 'endtime': endtime });
        return this.http.post(url, JSON.parse(params));
    }
    rowChange(e) {
        this.page = e;
        this.searchType();
    }
    alarmCommand(data) {
        this.router.navigate(['control/diagnose'], {
            queryParams: {
                'NID': data.nid,
                'STATIONID': data.stationid ? data.stationid : '',
                'STATIONNAME': data.stationname ? data.stationname : '',
                'ALARMLEVEL': data.alarmlevel ? data.alarmlevel : '',
                'ALARMTEXT': encodeURI(encodeURI(data.alarmtext ? data.alarmtext : '')),
                'ALARMTYPE': data.alarmtype ? data.alarmtype : '',
                'DEVTYPEID': data.devType ? data.devType : '',
                'DEVTYPE': encodeURI(encodeURI(data.devTypeName ? data.devTypeName : '')),
                'DEVNAME': encodeURI(encodeURI(data.devname ? data.devname : '')),
                'TIME': data.nTime ? data.nTime : '',
                'ALARMDESCRIPTION': ''
            }
        });
    }

    getjcbjtype(devName) {
        if (!devName) {
            return;
        }
        this.bjlxList = [];
        this.bjlxValue = '';

        this.controlApiService.getjcbjtype(devName).subscribe((resdata: any) => {
            if (resdata.length) {
                switch (resdata[0].children) {
                    case undefined: case 'undefined': case null: case 'null': case false: case 'false':
                        this.bjlxValue = resdata[0].id;
                        break;
                    default:
                        this.bjlxValue = resdata[0].children[0].id;
                        break;
                }
                this.bjlxList = resdata;
            }
        });
    }
} 